// 初始化公司账单类型SQL
import {CompanyBillCategoryId, CompanyBillCategoryName} from "../roleTypes/CompanyBillCategory.js";
import categoryDao from "./category.js";
import sequelize from "../models/init.js";
import {UserBillCategory, UserBillCategoryName} from "../roleTypes/UserBillCategory.js";


async function init() {
  let res = await categoryDao.getCompanyCategory(0);
  // console.log(res, '公司默认账单类型');
  let res2 = await categoryDao.getUserCategory(0);
  // console.log(res2, '用户默认账单类型');
  const t = await sequelize.transaction();
  res.length === 0 && await initCompanyBillTypes(t);
  res2.length === 0 && await initUserBillTypes(t);
  await t.commit();
  console.log('初始化账单类型完成');
  (res.length === 0) && await async function () {
    res = await categoryDao.getCompanyCategory(1);
    console.log(res, '公司账单类型');
  }();
  (res2.length === 0) && await async function (){
    res2 = await categoryDao.getUserCategory(1);
    console.log(res2, '用户账单类型');
  }();
}

init();

async function initCompanyBillTypes(t) {
  let ids = Object.values(CompanyBillCategoryId);
  for (let i = 0; i < ids.length; i++) {
    let id = ids[i];
    let name = CompanyBillCategoryName[id];
    let is_out = getDefaultIsOut(id);
    try {
      await categoryDao.addCompanyDefaultCategory(id, name, is_out, t);
    } catch (e) {
      console.log(e, 'initCompanyBillTypes Error');
      await t.rollback();
      throw new Error('初始化公司账单类型失败');
    }
  }
  console.log('initCompanyBillTypes Success');
}

// 初始化用户账单类型SQL
async function initUserBillTypes(t) {
  let ids = Object.values(UserBillCategory);
  for (let i = 0; i < ids.length; i++) {
    let id = ids[i];
    let name = UserBillCategoryName[id];
    let is_out = getDefaultIsOut(id);
    try {
      await categoryDao.addUserDefaultCategory(id, name, is_out, t);
    } catch (e) {
      console.log(e, 'initUserBillTypes Error');
      await t.rollback();
      throw new Error('初始化用户账单类型失败');
    }
  }
  console.log('initUserBillTypes Success');
}


function getDefaultIsOut(id) {
  let obj = {
    // 公司
    99: 1, // 支出类型 <=99
    999: 0, // 收入类型 <=999
    1000: 1, // 其他支出
    1001: 0, // 其他收入
    // 用户
    10099: 1, // 支出类型 <=10099
    10999: 0, //  收入类型 <=10999
    11000: 1, // 其他支出
    11001: 0, // 其他收入
  };
  let keys = Object.keys(obj).sort((a, b) => (a - b));
  for (let i = 0; i < keys.length; i++) {
    if (id <= keys[i]) {
      return obj[keys[i]];
    }
  }
  throw new Error('公司收入支出类型获取错误');
}
